#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date    : 2016-11-10 18:12:56
# @Author  : PiaoYun (piaoyunsoft@163.com)
# @Link    : http://www.dllhook.com
# @Version : 1.0.0.1
# @Comment : PyCrypto库RSA加密、解密、签名演示

# 弊端 -- 只能公钥加密、私钥解密~~  不能做keygen

from Crypto import Random
from Crypto.Hash import SHA
from Crypto.Cipher import PKCS1_v1_5 as Cipher_pkcs1_v1_5
from Crypto.Signature import PKCS1_v1_5 as Signature_pkcs1_v1_5
from Crypto.PublicKey import RSA
import base64

# 伪随机数生成器
random_generator = Random.new().read

# 生成密钥对
def generate():
    # rsa算法生成实例
    rsa = RSA.generate(1024, random_generator)

    # 秘钥对的生成
    private_pem = rsa.exportKey()
    with open('private.pem', 'w') as f:
        f.write(private_pem)

    public_pem = rsa.publickey().exportKey()
    with open('public.pem', 'w') as f:
        f.write(public_pem)

# 公钥加密
def encrypt(plain_text):
    with open('public.pem') as f:
        key = f.read()
        rsakey = RSA.importKey(key)
        print rsakey.has_private()
        print rsakey.publickey()
        cipher = Cipher_pkcs1_v1_5.new(rsakey)
        cipher_text = base64.b64encode(cipher.encrypt(plain_text))
        #print cipher_text
        return cipher_text

# 私钥解密
def decrypt(cipher_text):
    with open('private.pem') as f:
        key = f.read()
        rsakey = RSA.importKey(key)
        cipher = Cipher_pkcs1_v1_5.new(rsakey)
        plain_text = cipher.decrypt(base64.b64decode(cipher_text), random_generator)
        #print text
        return plain_text

# 私钥签名
def signature(data):
    with open('private.pem') as f:
        key = f.read()
        rsakey = RSA.importKey(key)
        signer = Signature_pkcs1_v1_5.new(rsakey)
        digest = SHA.new()
        digest.update(data)
        #print digest.hexdigest()
        sign = signer.sign(digest)
        signature = base64.b64encode(sign)
        return signature
# 公钥验证
def verifySignature(data, signature):
    with open('public.pem') as f:
        key = f.read()
        rsakey = RSA.importKey(key)
        verifier  = Signature_pkcs1_v1_5.new(rsakey)
        digest = SHA.new()
        digest.update(data)
        #print digest.hexdigest()
        is_verifier = verifier.verify(digest, base64.b64decode(signature))
        return is_verifier

if __name__ == '__main__':
    generate()

    plain_text = 'piaoyun|piaoyunsoft@163.com|999|8888-8888-8888-8888|2099-11-10'

    cipher_text = encrypt(plain_text)
    print("RSA加密结果:\n%s"%cipher_text)

    plain_text = decrypt(cipher_text)
    print("RSA解密结果:\n%s"%plain_text)

    sign = signature(plain_text)
    print("私钥签名:\n%s"%sign)

    if verifySignature(plain_text, sign):
    	print('签名正确，你是正版用户！')
    else:
        print('签名错误，你是盗版用户')